package com.topscomm.base.operation;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.topscomm.basic.BasicEntity;
import com.topscomm.tap.TapService;

/**
 * 多线程调度处理
 * 
 * @description:
 * @author: donghang
 * @date: 2020年10月28日下午6:53:12
 * @modify:
 */
public class BaseBatchExecutorService {
	/**
	 * 批量大小
	 */
	private int batchSize = 500;

	/**
	 * 
	 * @description:
	 * @param dataList
	 * @param batchNum
	 * @author: donghang
	 * @throws InterruptedException
	 * @date: 2020年10月28日下午7:03:20
	 * @modify:
	 */
	public void batchDeal(List<BasicEntity> dataList, TapService<?, ?> tapService) throws InterruptedException {
		int totalSize = dataList.size();
		int pageCount = totalSize % this.batchSize == 0 ? totalSize / batchSize : totalSize / batchSize + 1;
		ExecutorService executor = Executors.newFixedThreadPool(pageCount);
		try {
			CountDownLatch countDownLatch = new CountDownLatch(pageCount);
			List<BasicEntity> subData = null;
			int fromIndex, toIndex;
			for (int i = 0; i < pageCount; i++) {
				fromIndex = i * this.batchSize;
				toIndex = Math.min(totalSize, fromIndex + this.batchSize);
				subData = dataList.subList(fromIndex, toIndex);
				// 任务处理
				BaseBatchTask task = new BaseBatchTask(subData, tapService, countDownLatch);
				executor.execute(task);
			}
			countDownLatch.await();
		} finally {
			// 关闭线程池，释放资源
			executor.shutdown();
		}
	}
}
